<template>
	<div class="edit-popup">
		<popup ref="popupRef" :title="popupTitle" :async="true" width="550px" @confirm="handleSubmit"
			@close="handleClose">
			<el-tabs v-model="lang" @tab-change="handChange">
				<el-tab-pane v-for="(item, index) in languages.list" :key="index" :label="item.name" :name="item.symbol"
					lazy></el-tab-pane>
			</el-tabs>
			<el-form ref="formRef" :model="formData" label-width="84px" :rules="formRules">
				<el-form-item label="栏目名称" prop="name">
					<el-input v-model="formData.name" placeholder="请输入栏目名称" clearable />
					<el-button type="primary" size="small" v-if="active!=0" @click="handTranslation('name')"
						:loading="loadingTran">翻译</el-button>
				</el-form-item>
				<el-form-item label="排序" prop="sort">
					<div>
						<el-input-number v-model="formData.sort" :min="0" :max="9999" />
						<div class="form-tips">默认为0， 数值越大越排前</div>
					</div>
				</el-form-item>
				<el-form-item label="状态" prop="is_show">
					<el-switch v-model="formData.is_show" :active-value="1" :inactive-value="0" />
				</el-form-item>
			</el-form>
		</popup>
	</div>
</template>
<script lang="ts" setup>
	import type { FormInstance } from 'element-plus'
	import { articleCateEdit, articleCateAdd, articleCateDetail } from '@/api/article'
	import { translation } from '@/api/translation'
	import { apiLanguageAll } from '@/api/setting/language'
	import Popup from '@/components/popup/index.vue'
	import feedback from '@/utils/feedback'

	const emit = defineEmits(['success', 'close'])
	const formRef = shallowRef<FormInstance>()
	const popupRef = shallowRef<InstanceType<typeof Popup>>()
	const mode = ref('add')
	const popupTitle = computed(() => {
		return mode.value == 'edit' ? '编辑栏目' : '新增栏目'
	})

	const languages = reactive({
		list: [{
			id: '',
			name: '',
			symbol: ''
		}],
		symbol: ''
	})

	const active = ref(0);
	const lang = ref("");
	const lang_1 = ref("");//切换前一个
	let langs = reactive([]);

	const formData = reactive({
		id: '',
		name: '',
		sort: 0,
		is_show: 1,
		langs: []
	})

	const formRules = {
		name: [
			{
				required: true,
				message: '请输入栏目名称',
				trigger: ['blur']
			}
		]
	}

	const handleSubmit = async () => {
		await formRef.value?.validate()
		//数组存储
		let arr = {
			'lang': lang.value,
			'name': formData.name,
		}

		//数组更新
		let array = pushArr(langs, lang.value, arr);
		langs = array;

		//查询首个语言是否填写
		let exists = false;
		let langs_key = 0;
		Object.keys(langs).forEach((key) => {
			if (langs[key]['lang'] == languages.list[0]['symbol']) {
				if (langs[key]['name'] != "") {
					exists = true;
					langs_key = parseInt(key);
				}
			}
		})
		if (!exists) return feedback.msgError('首个语言必填');
		//输入初始化
		let arr2 = langs[langs_key];
		Object.keys(arr2).forEach((key) => {
			//@ts-ignore
			formData[key] = arr2[key]
		})

		formData.langs = langs;

		mode.value == 'edit' ? await articleCateEdit(formData) : await articleCateAdd(formData)
		popupRef.value?.close()
		emit('success')
	}

	const open = (type = 'add') => {
		mode.value = type
		popupRef.value?.open()
	}

	const setFormData = (data : Record<any, any>) => {
		for (const key in formData) {
			if (data[key] != null && data[key] != undefined) {
				//@ts-ignore
				formData[key] = data[key]
			}
		}
	}

	const getDetail = async (row : Record<string, any>) => {
		const data = await articleCateDetail({
			id: row.id
		})
		setFormData(data)
		langs = data['langs'];
	}

	const handleClose = () => {
		emit('close')
	}

	const getData = async () => {
		const data = await apiLanguageAll()
		languages.list = data;
		languages.symbol = data[0]['symbol'];
		lang.value = languages.symbol;
	}
	//数组替换，存在替换，不存在追加
	const pushArr = (arr : any, lang : string, params : any) => {
		let result = false;
		Object.keys(arr).forEach((key) => {
			if (arr[key]['lang'] == lang) {
				arr[key] = params;
				result = true;
			}
		})

		if (!result) {
			arr.push(params);
		}
		return arr;
	}
	//标签切换
	const handChange = async (data : string) => {
		let lang_last = lang_1.value;
		lang_1.value = data
		const index = languages.list.findIndex((item) => item.symbol === data);
		active.value = index;

		//数组存储
		if (lang_last != "") {
			let arr = {
				'lang': lang_last,
				'name': formData.name,
			}
			let array = pushArr(langs, lang_last, arr);
			langs = array;
		}
		//输入初始化
		let arr2 = {
			'lang': "",
			'name': "",
		}
		Object.keys(langs).forEach((key) => {
			if (langs[key]['lang'] == data) {
				arr2 = langs[key];
			}
		})

		if (lang_last != "") {
			Object.keys(arr2).forEach((key) => {
				//@ts-ignore
				formData[key] = arr2[key]
			})
		}
		if (localStorage.getItem('trans_auto') == '1' && formData.name == '' && active.value != 0) {
			handTranslation('name')
		}
	}

	//翻译
	const loadingTran = ref(false);
	const handTranslation = async (field : string) => {

		//查询首个语言是否填写
		let exists = false;
		let langs_key = 0;

		Object.keys(langs).forEach((key) => {
			if (langs[key]['lang'] == languages.list[0]['symbol']) {
				if (langs[key][field] != "") {
					exists = true;
					langs_key = parseInt(key);
				}
			}
		})

		if (!exists) return feedback.msgError('首个语言必填');
		const qArray = [langs[langs_key][field]]

		loadingTran.value = true;
		const res = await translation({
			qArray: qArray,
			from: languages.list[0]['trans_symbol'],
			to: languages.list[active.value]['trans_symbol']
		})
		formData[field] = res['result'][0]['translation'];
		loadingTran.value = false;
	}

	defineExpose({
		open,
		setFormData,
		getDetail
	})
	getData()
</script>